export function getType(data) {
  const typeStr = Object.prototype.toString.call(data)
  return typeStr.substring(8, typeStr.length - 1).toLowerCase()
}

export function deepClone(data) {
  let target;
  if (Array.isArray(data)) {
    target = [];
  } else if (getType(data) === 'object') {
    target = {};
  } else {
    return data
  }
  for (let key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const value = data[key];
      if (typeof value === 'object' && value !== null) {
        target[key] = deepClone(value)
      } else {
        target[key] = value;
      }
    }
  }
  return target;
}

// 清除为空的参数、清除字符串的前后空格
export function formatParameter(params, method = 'get') {
  for (let key in params) {
    if (
      params[key] === undefined ||
      params[key] === null ||
      (params[key] === '' && method.toLowerCase() === 'get')
    ) {
      delete params[key]
    } else if (typeof params[key] === 'string') {
      params[key] = params[key].replace(/(^\s*)|(\s*$)/g, '')
    }
  }
}

// 创建formdata格式的数据
export function createFormData(data) {
  if (data instanceof FormData) return data;
  const formData = new FormData();
  for (let k in data) {
    if (Object.prototype.hasOwnProperty.call(data, k)) {
      // FormData仅支持基本类型数据，引用类型的会调用其toString方法，所以要单独处理
      const item = data[k]
      if (Array.isArray(item)) {
        item.forEach(v => {
          formData.append(k, v)
        })
      } else {
        formData.append(k, data[k])
      }
    }
  }
  return formData;
}

export function aLinkDownload(obj) {
  const a = document.createElement('a');
  a.download = obj.fileName;
  if (obj.href) {
    a.href = obj.href
    a.click();
  } else if (obj.blob) {
    a.href = window.URL.createObjectURL(obj.blob);
    a.click();
    window.URL.revokeObjectURL(a.href);
  } else {
    console.error('href 和 blob 参数至少需要一个')
  }
}

// 应用中对金额的统一处理
const PRECISION = 2; // 两位小数
export function mult(num, precision = PRECISION) {
  num = Number(num) || 0;
  const power = Math.pow(10, precision);
  return Math.round(num * power);
}

export function divi(num, precision = PRECISION) {
  num = '00' + parseInt(num);
  const int = num.substring(0, num.length - precision)
  const float = num.substring(num.length - precision)
  return Number(int + '.' + float);
}

// 百分比保留2位小数 0.0457 -> 4.57%
export function percent(num, precision = PRECISION) {
  num = Number(num) || 0;
  const multiNum = (num * 100).toFixed(precision)
  return String(multiNum) + '%'
}

// 数字转中文大写
export const number2text = (number, type = "upper") => {
  if (typeof number !== "number" || isNaN(number)) return '';

  if (number === 0) return '零元';
  // 配置
  const confs = {
    lower: {
      num: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
      unit: ["", "十", "百", "千", "万"],
      level: ["", "万", "亿"]
    },
    upper: {
      num: ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"],
      unit: ["", "拾", "佰", "仟"],
      level: ["", "万", "亿"]
    },
    decimal: {
      unit: ["分", "角"]
    },
    maxNumber: 999999999999.99
  };

  // 过滤不合法参数
  if (Number(number) > confs.maxNumber) {
    console.error(
      `The maxNumber is ${confs.maxNumber}. ${number} is bigger than it!`
    );
    return false;
  }

  const conf = confs[type];
  const numbers = String(Number(number).toFixed(2)).split(".");
  const integer = numbers[0].split("");
  const decimal = Number(numbers[1]) === 0 ? [] : numbers[1].split("");

  // 四位分级
  const levels = integer.reverse().reduce((pre, item, idx) => {
    let level = pre[0] && pre[0].length < 4 ? pre[0] : [];
    let value =
      item === "0" ? conf.num[item] : conf.num[item] + conf.unit[idx % 4];
    level.unshift(value);

    if (level.length === 1) {
      pre.unshift(level);
    } else {
      pre[0] = level;
    }

    return pre;
  }, []);

  // 整数部分
  const _integer = levels.reduce((pre, item, idx) => {
    let _level = conf.level[levels.length - idx - 1];
    let _item = item.join("").replace(/(零)\1+/g, "$1"); // 连续多个零字的部分设置为单个零字

    // 如果这一级只有一个零字，则去掉这级
    if (_item === "零") {
      _item = "";
      _level = "";

      // 否则如果末尾为零字，则去掉这个零字
    } else if (_item[_item.length - 1] === "零") {
      _item = _item.slice(0, _item.length - 1);
    }

    return pre + _item + _level;
  }, "");

  // 小数部分
  let _decimal = decimal
    .map((item, idx) => {
      const unit = confs.decimal.unit;
      const _unit = item !== "0" ? unit[unit.length - idx - 1] : "";

      return `${conf.num[item]}${_unit}`;
    })
    .join("");

  return `${_integer}元` + _decimal;
};